package com.xhai.common.domain;

import com.xhai.common.enums.AppHttpCodeEnum;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;

import java.io.Serial;
import java.io.Serializable;

/**
 * @author xhai
 * @description 统一响应返回格式基类
 * @date 2025/5/24
 */
@Data
@Schema(description = "统一响应返回格式基类")
public class ResponseResult<T> implements Serializable {
    @Serial
    private static final long serialVersionUID = -5707072856677715277L;

    /**
     * 响应码
     */
    @Schema(description = "响应码")
    private Integer code;

    /**
     * 响应消息
     */
    @Schema(description = "响应消息")
    private String msg;

    /**
     * 数据
     */
    @Schema(description = "数据")
    private T data;

    private ResponseResult(Integer code, T data) {
        this.code = code;
        this.data = data;
    }

    private ResponseResult(Integer code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    private ResponseResult(Integer code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    /**
     * 根据AppHttpCodeEnum响应
     *
     * @param enums 统一响应返回编码
     * @return 响应实体类
     */
    private static <T> ResponseResult<T> setAppHttpCodeEnum(AppHttpCodeEnum enums) {
        return new ResponseResult<>(enums.getCode(), enums.getMsg());
    }

    /**
     * 不带数据的成功响应
     *
     * @return 响应实体类
     */
    public static <T> ResponseResult<T> success() {
        return setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 带数据的成功响应
     *
     * @param data 返回数据
     * @return 响应实体类
     */
    public static <T> ResponseResult<T> success(T data) {
        ResponseResult<T> responseResult = setAppHttpCodeEnum(AppHttpCodeEnum.SUCCESS);
        responseResult.setData(data);
        return responseResult;
    }

    /**
     * 通用失败响应
     *
     * @return 响应实体类
     */
    public static <T> ResponseResult<T> fail() {
        return setAppHttpCodeEnum(AppHttpCodeEnum.FAIL);
    }

    /**
     * 根据AppHttpCodeEnum失败响应
     *
     * @param enums 统一响应返回编码
     * @return 响应实体类
     */
    public static <T> ResponseResult<T> fail(AppHttpCodeEnum enums) {
        return setAppHttpCodeEnum(enums);
    }

    /**
     * 自定义响应消息的失败响应
     *
     * @param msg 响应消息
     * @return 响应实体类
     */
    public static <T> ResponseResult<T> fail(String msg) {
        ResponseResult<T> responseResult = setAppHttpCodeEnum(AppHttpCodeEnum.FAIL);
        responseResult.setMsg(msg);
        return responseResult;
    }

    /**
     * 自定义响应消息的失败响应
     *
     * @param code 响应码
     * @param msg 响应信息
     * @return 响应实体类
     */
    public static <T> ResponseResult<T> fail(int code, String msg) {
        return new ResponseResult<>(code, msg);
    }
}
